package com.yld.demo.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yld.demo.entity.OrderList;
import com.yld.demo.entity.PageBean;
import com.yld.demo.mapper.OrderListMapper;
import com.yld.demo.service.OrderListService;
import com.yld.demo.util.redis.CacheClient;
import com.yld.demo.util.redis.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class OrderListServiceImpl extends ServiceImpl<OrderListMapper, OrderList> implements OrderListService {
    @Autowired
    OrderListMapper orderListMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    CacheClient cacheClient;


    @Override
    public PageBean<OrderList> getOrderList(PageBean<OrderList> pageBean) throws InterruptedException, ParseException {
        IPage iPage = new Page(pageBean.getCurrentPage(), pageBean.getRows());
        //经过MP分页查询将所有的分页(total/结果/页面/条数/xxx)数据封装到iPage对象
        iPage = queryPageWithLogicalExpire(iPage);

        //从分页对象中获取总记录数
        long total = iPage.getTotal();
        //从分页对象中获取分页后的结果
        List rows = iPage.getRecords();
        pageBean.setList(rows);
        pageBean.setTotalCount(total);
        pageBean.setTotalPage(iPage.getPages());
        return pageBean;    //需要返回的是5个参数
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public IPage queryPageWithLogicalExpire(IPage iPage) throws InterruptedException {
        String key = "orderpage:" + iPage.getCurrent() + ":" + iPage.getSize();
        //1.从redis缓存查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在 isBlank
        if (StrUtil.isBlank(json)) {
            if ("".equals(json)) {
                return null;
            }
            //3.不存在，查询数据库
            //3.1获取互斥锁
            String lockKey = "lock" + key;
            boolean isLock = tryLock(lockKey);
            //6.2判断是否获取锁成功
            if (isLock) {
                //TODO 3.3成功，开启独立线程
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        //查询数据库
                        IPage page = orderListMapper.selectPage(iPage, null);
                        //写入redis
                        //5.不存在，返回404
                        if (page == null) {
                            //将空值写入redis，防止缓存穿透
                            stringRedisTemplate.opsForValue().set(key, "", 30L, TimeUnit.SECONDS);
                            //返回错误信息
                        } else {
                            //写入redis
                            cacheClient.setWithLogicalExpire(key, page, 2L, TimeUnit.MINUTES);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //释放锁
                        unLock(lockKey);
                    }
                });
            }
            Thread.sleep(200);
            return queryPageWithLogicalExpire(iPage);
        }
        //4.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        String data = JSONUtil.toJsonStr(redisData.getData());
        IPage r = JSONUtil.toBean(data,Page.class);
        List<OrderList> rows = new ArrayList<>();
        List list = r.getRecords();
        for (Object o : list) {
            String s = JSONUtil.toJsonStr(o);
            OrderList orderList = JSONUtil.toBean(s, OrderList.class);
            rows.add(orderList);
        }
        r.setRecords(rows);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1未过期，直接返回信息
            return r;
        }
        //5.2已过期，需要缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = "lock" + key;
        boolean isLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (isLock) {
            //TODO 6.3成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    IPage page = orderListMapper.selectPage(iPage, null);
                    //写入redis
                    cacheClient.setWithLogicalExpire(key, page, 2L, TimeUnit.MINUTES);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4返回过期的信息
        return r;
    }


    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);

    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public OrderList selectById(Integer orderNo) throws InterruptedException {
        OrderList orderList = cacheClient.queryWithLogicalExpire("order", orderNo, OrderList.class, this::getById, 2L, TimeUnit.MINUTES);
        return orderList;
    }

    public List<OrderList> selectByUserId(Integer userId, String startDate, String endDate) {
        //准备
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = df.parse(startDate);
            date2 = df.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //key采取  开始时间:结束时间:用户id
        String key = date1 + ":" + date2 + ":" + userId.toString();
        //1.从redis查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        System.out.println(json);
        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在，直接返回
            //这段是将json解析为jsonArray对象，该对象可以存多个json元素，tolist将jsonArray对象转化为OrderList对象列表
            List<OrderList> list = JSONUtil.parseArray(json).toList(OrderList.class);
            return list;
        }
        //4.判读命中是否是空值，解决缓存穿透
        if (json != null) {
            //返回错误信息
            return null;
        }

        //5.如果redis查不到，查数据库，条件查询
        QueryWrapper<OrderList> orderListWrapper = new QueryWrapper<>();
        orderListWrapper.eq("user_id", userId);
        orderListWrapper.between("order_date", date1, date2);
        //6.将查到的所有订单号放到集合
        List<OrderList> list = orderListMapper.selectList(orderListWrapper);
        //7.添加到redis
        cacheClient.set(key, list, 30L, TimeUnit.MINUTES);
        return list;
    }

    @Override
    public List<OrderList> selectAll() {
        QueryWrapper<OrderList> queryWrapper = new QueryWrapper<OrderList>();
        queryWrapper.lambda().orderBy(true, false, OrderList::getOrderNo);
        List<OrderList> list = orderListMapper.selectList(queryWrapper);
        return list;
    }


    @Override
    public void delete(Integer orderNO) {
        stringRedisTemplate.delete("order" + orderNO.toString());
        UpdateWrapper<OrderList> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no", orderNO).set("enabled", 1);
        this.update(wrapper);
    }

    @Override
    public String UpdateOrderList(OrderList orderlist) {

        LambdaQueryWrapper<OrderList> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(OrderList::getOrderNo, orderlist.getOrderNo());

        if (this.update(orderlist, queryWrapper)) {
            stringRedisTemplate.delete("order" + orderlist.getOrderNo().toString());
            return "修改成功!";
        } else {
            return "修改失败!";
        }
    }
}
